/*
 * Middleware
 * Copyright (C) 2010/11
 * Marco Buzzanca, Davide Giuseppe Monaco, Riccardo Pulvirenti, Giuseppe Ravidà,
 * Andrea Tino
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANDABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses
 */

/*!
 * File: file_cta_proxy.cpp
 */

#include "file_cta_proxy.hpp"

using namespace middleware;

//-----------------------------------------------------------------------------
// Constructors and destructor
/* Passing filename */
FileCTAProxy::FileCTAProxy(CTAPort port, const std::string& filename) {
	this->_filename = filename;
	this->_open_mode = kOpenAppend;
	this->_port = port;
	// Run thread
	this->_listener.reset();
	this->_listener = boost::shared_ptr<boost::thread>(new boost::thread(
			boost::bind(&FileCTAProxy::exec_listen, this)));
}
/* Specifying open mode */
FileCTAProxy::FileCTAProxy(CTAPort port, const std::string& filename,
		FileCTAOpenMode open_mode) {
	this->_filename = filename;
	this->_open_mode = open_mode;
	this->_port = port;
	// Run thread
	this->_listener.reset();
	this->_listener = boost::shared_ptr<boost::thread>(new boost::thread(
			boost::bind(&FileCTAProxy::exec_listen, this)));
}
/* Destructor */
FileCTAProxy::~FileCTAProxy() { }
//-----------------------------------------------------------------------------
// Public members
/* Writing in file */
FileCTAProxy& FileCTAProxy::operator<<(const std::string& str) {
	boost::mutex::scoped_lock lck(this->_write); /* Lock */
	// Getting stream and writing
	std::ios_base::openmode mode;
	if (this->_open_mode == kOpenOverwrite)
			mode = std::ios_base::out | std::ios_base::trunc;
		else
			mode = std::ios_base::out | std::ios_base::app;
	std::fstream fs(this->_filename.c_str(), mode);
	fs << str; // In file
	fs.close();
	return *this;
}
//-----------------------------------------------------------------------------
// Private members
/* Agreement listener execution flow */
void FileCTAProxy::exec_listen() {
	using boost::asio::ip::tcp;
	try {
		boost::asio::io_service io_service;
		tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(),
				this->_port));
		// Mutex is not immediately locked, just declared
		boost::mutex::scoped_lock lock(this->_write, boost::defer_lock);
		std::string message;
		for (;;) {
			tcp::iostream stream;
			acceptor.accept(*stream.rdbuf()); // Accepting requests: blocks!
			std::getline(stream, message);
			// React when the message is a message to read
			if (message == kCTAProtocolReadRequest) {
				std::cout << "CTAProxy: Received token request!" << std::endl;
				lock.lock(); /* LOCK */
				stream << kCTAProtocolReadGranted << std::endl; // Give token
				std::cout << "CTAProxy: Token sent!" << std::endl;
				std::getline(stream, message); /* Wait to get a line *** */
				if (message == kCTAProtocolReadDone) {
					std::cout << "CTAProxy: Got token back!" << std::endl;
					lock.unlock(); /* Unlock */
				}
			} // If the message is not a request, do not give token
		}
	} catch (std::exception& e) {
		std::cout << e.what() << std::endl;
	}
}
